/**=========================================================
 * Service: httpUtils.js
 * Utility library to use across the theme
 =========================================================*/

App.service('HttpUtils', ["$rootScope", "$http", '$q', "Utils",
    function($rootScope, $http, $q, utils) {
        'use strict';
                  
        return {
            queryList: function(params,successFn,failureFn){
                this.get('/common/queryList',params,successFn,failureFn);
            },
            get: function(path,params,successFn,failureFn) {
                //get方法中文乱码
                this.post(path,params,successFn,failureFn);
            },
            post: function(path,params,successFn,failureFn) {
                if ($rootScope.app.isSessionValid){
                    if (utils.isEmpty(failureFn)){
                        failureFn = function(){};
                    }
                    $http({
                        url: utils.getBackendPath(path),
                        method: 'POST',
                        timeout: 60000,
						withCredentials: true, // 跨域
                        headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf8'},
                        transformRequest: function(obj) {
                            var str = [];
                            for(var p in obj)
                            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                            return str.join("&");
                        },
                        data: params
                    }).then(function(response){
                        var result = response.data;
                        if (result.isValid == 'false'){
                            if($rootScope.$state.current.name != 'page.login'){
                                //第一次发现session过期
                                $rootScope.app.user = {};
                                $rootScope.app.isSessionValid = false;
                                $rootScope.stateToGo = $rootScope.$state.current.name;
                                $rootScope.$state.go('page.login');
                            }
                            return;
                        }
                        if (!utils.isEmpty(successFn))
                            successFn.call(this,result);
                    }).catch(failureFn);
                }else{
                    console.log('Invalid Session')
                } 
            },
            promise: function(path,params){
                var deferred = $q.defer();
                $http.get(utils.getBackendPath(path),{withCredentials: true}).then(
                    function(result) {
                        deferred.resolve(result);
                    },
                    function(data, status, headers, config) {
                        deferred.reject(data);
                    }
                );
                return deferred.promise;
            }
        };
    }
]);